var express = require("express");
var router = express.Router();
var moment = require("moment");
const Role = require("../db/model/roleModel");
const {Op} = require('sequelize')
const {success,fail,successWithData} = require("../utils/result")

/**
 * @api {POST} /role/add 角色添加
 * @apiDescription 角色添加
 * @apiName add
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Role
 * @apiBody {String} role_name      角色名
 * @apiBody {String} desc           角色描述
 * @apiBody {String} permission_ids 权限ids
 * @apiBody {Number} state=0        1 启用 0 禁用
 * @apiParamExample {json} Request-Example:
 *     {
 *        "role_name": "超级管理员",
 *        "desc": "最高权限管理员",
 *        "permission_ids": "1,2,3,4",
 *        "state": 1
 *     }
 * @apiVersion 1.0.0
 */
router.post("/role/add", async (req, res) => {
  try {
    let { role_name, desc, permission_ids } = req.body;
    if (!role_name) {
      return res.send(fail("缺少参数"));
    }
    let data = await Role.findAll({
      where: {
        role_name,
      },
    });
    if (data.length > 0) {
      return res.json(fail("角色名已存在"));
    }
    let time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    let result = await Role.create({
      role_name,
      permission_ids,
      desc,
      state: 1,
      create_time: time,
      updated_time: time,
    });
    console.log("添加角色:", result);
    return res.json(success());
  } catch (err) {
    return res.json(fail("创建失败:" + err));
  }
});

/**
 * @api {POST} /role/edit 角色编辑
 * @apiDescription 角色编辑
 * @apiName edit
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Role
 * @apiBody {Number} id=1 角色id
 * @apiBody {String} role_name="超级管理员"    角色名
 * @apiBody {String} desc="最高权限管理员"     角色描述
 * @apiBody {String} permission_ids="1,2,3,4" 权限ids
 * @apiBody {Number} state=0                  1 启用 0 禁用
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "role_name": "超级管理员",
 *        "desc": "最高权限管理员",
 *        "permission_ids": "1,2,3,4",
 *        "state": 1
 *     }
 * @apiVersion 1.0.0
 */
router.post("/role/edit", async (req, res) => {
  try {
    let { id, role_name, desc, state, permission_ids } = req.body;
    if (!id) {
      return res.send(fail("缺少id参数"));
    }
    let one = await Role.findOne({
      where: {
        id,
      },
    });
    console.log("查询角色数据", one);
    if (!one) {
      return res.json(fail("角色不存在"));
    }
    let data = one.dataValues;
    if (role_name) {
      data.role_name = role_name;
    }
    if (desc) {
      data.desc = desc;
    }
    if (state === 0 || state === 1) {
      data.state = state;
    }
    if (permission_ids) {
      data.permission_ids = permission_ids;
    }
    data.updated_time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    console.log("角色保存数据", data);

    let result = await Role.update(data, {
      where: {
        id,
      },
    });
    console.log("编辑角色:", result);
    return res.json(success());
  } catch (err) {
    return res.json(fail("编辑失败:" + err));
  }
});

/**
 * @api {POST} /role/del 角色删除
 * @apiDescription 角色删除
 * @apiName del
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Role
 * @apiBody {Number} id=1 角色id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1
 *     }
 * @apiVersion 1.0.0
 */
router.post("/role/del", async (req, res) => {
  try {
    let { id } = req.body;
    if (!id) {
      return res.send(fail("缺少id参数"));
    }

    let result = await Role.destroy({
      where: {
        id,
      },
    });
    console.log("角色删除", result);

    return res.json(success());
  } catch (err) {
    return res.json(fail("删除失败:" + err));
  }
});

/**
 * @api {POST} /role/setPermission 角色设置权限
 * @apiDescription 角色设置权限
 * @apiName setPermission
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup Role
 * @apiBody {Number} id=1 角色id
 * @apiBody {String} permission_ids="1,2,3,4" 权限ids
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "permission_ids": "1,2,3,4"
 *     }
 * @apiVersion 1.0.0
 */
router.post("/role/setPermission", async (req, res) => {
  try {
    let { id, permission_ids } = req.body;
    if (!id || !permission_ids) {
      return res.send(fail("缺少参数"));
    }

    let result = await Role.update(
      {
        permission_ids,
        updated_time: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      },
      {
        where: {
          id,
        },
      }
    );
    console.log("角色设置权限", result);

    return res.json(success());
  } catch (err) {
    return res.json(fail("权限设置失败:" + err));
  }
});

/**
 * 分页查询角色接口
 * @api {POST} /role/queryRoleByPage 分页查询角色接口
 * @apiDescription 分页查询角色接口
 * @apiName queryRoleByPage
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} page=1   页码
 * @apiBody {Number} limit=10   每页条数
 * @apiBody {String} role_name  角色名字
 * @apiParamExample {json} Request-Example:
 *     {
 *        "page": 1,
 *        "limit": "10",
 *        "role_name": "超级管理员"
 *     }
 * @apiGroup Role
 * @apiVersion 1.0.0
 */
 router.post('/role/queryRoleByPage', async function (req, res) {
  page = req.body.page
  limit = req.body.limit
  let offset = (page - 1) * limit;
  let where = {};
  if (req.body.role_name) {
      where['role_name'] = {
          [Op.like]: '%' + req.body.role_name + '%'
      }
  }
  try {
      const result = await Role.findAndCountAll({
          where,
          order: [
              ['created_time', 'DESC']
          ],
          limit,
          offset
      });
      return res.json(successWithData(result))
  } catch (error) {
      console.log(error);
      return res.json(fail(error))
  }
});

module.exports = router;
